<?php
namespace app\index\controller;

use app\index\model\Share;
use app\index\model\User;
use think\Db;
use think\Request;
use app\index\model\Thread;
use app\index\model\Like;
use app\index\model\Album;
use app\index\model\Post;
class Index extends Base
{
    public function index()
    {
		$arrname = Album::all(["tid"=>49]);
		print_r($arrname->toArray() );
        return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V5.1<br/><span style="font-size:30px">12载初心不改（2006-2018） - 你值得信赖的PHP框架</span></p></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=64890268" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="eab4b9f840753f8e7"></think>';
    }

    //首页导航模块
    public function mode()
    {
        $mode = Db::name("mode")->where("status",1)->select();

        $data['data'] = $mode;
        $data['msg']  = "获取成功";

        return $this->_toSuccess($data);
    }

    //首页推荐
    public function recommend()
    {
        $today = date("Y-m-d H:i:s",strtotime("today"));

        $data = Db::name("digital")
            ->where("created_at",">=",$today)
            //->where("type",1) //关闭视频类目
            ->order("like","desc")
            ->limit(2)
            ->select();
        $recommend['data'] = $data;
        $recommend['msg'] = '获取成功';

        return $this->_toSuccess($recommend);
    }
    
    //列表页
    public function lists()
    {
        $type = \request()->post("type") ?? 1;
        $page = \request()->post("page") ?? 1;

        $pageSize = ($page - 1) * 15;

        $list = Db::name("digital")
            ->where("type",$type)
            ->order("id","desc")
            ->limit($pageSize,15)
            ->select();
        $data['data'] = $list;
        $data['msg'] = '获取成功~';
        return $this->_toSuccess($data);
    }

    //详情页数据
    public function detail()
    {
        $digital_id = \request()->post("id");
        $uid = \request()->post("uid");

        //资源数据
        $digital_detail = Db::name("digital")
            ->where("id",$digital_id)
            ->find();

        //查询我是否点赞
        $myLike = Db::name("like")
            ->where("uid",$uid)
            ->where("digital_id",$digital_id)
            ->find();

        if($myLike){
            $digital_detail['mylike'] = true;
        }else{
            $digital_detail['mylike'] = false;
        }

        //猜你喜欢
        $likes = Db::name("digital")
            ->where("type",$digital_detail['type'])
            ->orderRand()
            ->limit(3)
            ->select();

        $data['detail'] = $digital_detail;
        $data['likes']  = $likes;
        $data['msg']    = '获取成功';

        return $this->_toSuccess($data);
    }
    
    
    //获取详情页评论
    public function comments()
    {
        $digital_id = \request()->post("id");

        $comments = Db::name("comment")
            ->alias("c")
            ->join("user u","c.uid = u.id")
            ->where("c.digital_id",$digital_id)
            ->order("c.id","desc")
            ->field("u.nickname,u.avatar,c.content,c.created_at")
            ->select();

        $data['comments'] = $comments;
        $data['msg']      = "获取成功";

        return $this->_toSuccess($data);


    }

    //发布评论
    public function addComment()
    {

        $digital_id = \request()->post("digital_id");
        $uid        = \request()->post("uid");
        $content        = \request()->post("content");
        $number     = 1;  //默认1金币

        if (!$digital_id) {
            $data['msg'] = "资源id不能为空~";
            return $this->_toError($data);
        }

        if (!$content) {
            $data['msg'] = "内容不能为空~";
            return $this->_toError($data);
        }

        if (!$uid) {
            $data['msg'] = "用户id不能为空~";
            return $this->_toError($data);
        }

        $today = date("Y-m-d H:i:s",strtotime("today"));
        $check = Db::name("comment")
            ->where("uid",$uid)
            //->where("digital_id",$digital_id)
            ->where("created_at",'>=',$today)
            ->find();

        //如果没有评论
        if (!$check) {
            Db::name("user")->where("id",$uid)->setInc('point',$number);
            Db::name("point")
                ->insert([
                    'uid'    => $uid,
                    'type'   => 1,
                    'number' => $number,
                    'digital_id' => $digital_id,
                    'remark' => '评论金币',
                    'created_at' => date("Y-m-d H:i:s",time())
                ]);
        }

        //更新digital表评论数据
        Db::name("digital")->where("id",$digital_id)->setInc('comment');


        //写入评论表
        Db::name("comment")
            ->insert([
                'digital_id' => $digital_id,
                'uid'        => $uid,
                'content'    => $content,
                'created_at' => date("Y-m-d H:i:s",time())
            ]);

        $data['msg'] = "评论成功~";
        return $this->_toSuccess($data);

    }


    //点赞
    public function addLike()
    {
        $digital_id = \request()->post("digital_id");
        $uid        = \request()->post("uid");
        $number     = 1;

        if (!$digital_id) {
            $data['msg'] = "资源id不能为空~";
            return $this->_toError($data);
        }
        if (!$uid) {
            $data['msg'] = "用户id不能为空~";
            return $this->_toError($data);
        }
        $today = date("Y-m-d H:i:s",strtotime("today"));
        $check = Db::name("like")
            ->where("uid",$uid)
            //->where("digital_id",$digital_id)
            ->where("created_at",'>=',$today)
            ->count();
        //如果今日点赞次数少于3 赠送金币
        if ($check <= 3) {
            Db::name("user")->where("id",$uid)->setInc('point',$number);
            Db::name("point")
                ->insert([
                    'uid'    => $uid,
                    'type'   => 1,
                    'number' => $number,
                    'digital_id' => $digital_id,
                    'remark' => '点赞金币',
                    'created_at' => date("Y-m-d H:i:s",time())
                ]);
        }

        //更新digital表点赞数据
        Db::name("digital")->where("id",$digital_id)->setInc('like');


        //写入点赞表
        Db::name("like")
            ->insert([
                'digital_id' => $digital_id,
                'uid'        => $uid,
                'created_at' => date("Y-m-d H:i:s",time())
            ]);

        $data['msg'] = "点赞成功~";
        return $this->_toSuccess($data);


    }


    public function hello($name = 'ThinkPHP5')
    {

        User::update(['point'=>time()],['id'=>1]);
        dump(User::get(1));

    }
	//点赞
    public function like()
    {
		$tid = input('tid');
		$uid = input('uid');
	    $arr = Like::get(["tid"=>$tid,"uid"=>$uid,"pid"=>0]);
		if($arr){
			 $res = $arr->delete();
			 if($res){
				Thread::get($tid)->setDec('goodnums',2);
				$this->makePoint($uid,$tid,11);//积分
				Like::destroy(['uid' => $uid,'tid' => $tid,'pid' => 0]);
				return $this->_toError(['msg' => '取消成功']);
				
			}else{
				return $this->_toError(['msg' => '取消失败']);
			}
		}else{
			$like           = new Like;
			$like->tid     = $tid;
			$like->uid    = $uid;
			$like->atime    = time();
			$res = $like->save();
			if($res){
				Thread::get($tid)->setInc('goodnums',2);
				$this->makePoint($uid,$tid,4);//积分
				return $this->_toError(['msg' => '点赞成功']);
			}else{
				return $this->_toError(['msg' => '点赞失败']);
			}
			
		}
	}
	//获取所有帖子
    public function loadThread()
    {
        $typeid  =  input('typeid');
		$uid  =  input('uid');
		$hot  =  input('hot');
		$page  =  input('page');
		if($typeid==0){
			if($hot==0){
				Thread::where('status','>',0)->count();
			}else{
				Thread::where('status','>',0)->count();
			}
			
		}else{
			Thread::where('status','>',0)->count();
		}
		
		
	}	
	//获取指定帖子
    public function info()
    {
		$tid = input('tid');
		$uid = input('uid');
		$url = input('url');
		$user = Thread::get($tid);
		$arr = $user->toArray();
		//获取发帖人信息
		$arrname = User::get($user['authorid']);
		$arr['url'] = $arrname['avatar'];
		$arr['author'] = $arrname['nickname'];
		//查看是否点赞当前用户
		$arrlike = Like::get(["tid"=>$arr['tid'],"uid"=>$uid,"pid"=>0]);
		$arr['like'] = $arrlike ? 1 : 0;
		//查询帖子是否有图片
		$arrname = Album::all(["tid"=>$tid]);
		
		if($arrname){
			$arrname = $arrname->toArray();
			$images = [];
			foreach($arrname as $arrn){
				$images[] = $url."/album/".$arrn['dir']."/".$arrn['filename'];
			}

		//print_r($images);exit;
			$arr['imgList'] = $images;
			$arr['img_num'] = count($images);
		}else{
			$arr['img_num'] = 0;
			$arr['imgList'] = "";
		}
		//查询回复
		$list = Post::all(function($query) use($tid){
					$query->where('tid',$tid)->limit(4)->order('pid', 'desc');
				});
		$list = $list->toArray();
		//关联用户头像 用户名
		$lists = [];
		foreach($list as $usr){
			$arrname = User::get($usr['authorid']);
			$usr['url'] = $arrname['avatar'];
			$usr['author'] = $arrname['nickname'];
			//查询是否点赞
			$arrlike = Like::get(["tid"=>$arr['tid'],"uid"=>$uid,"pid"=>$usr['pid']]);
			$usr['like'] = $arrlike ? 1 : 0;
			$lastime = strtotime($usr['create_time']);
			$usr['lastime'] = $this->lastime($lastime);
			$lists[] = $usr;
		}
		//$arr['list'] = $list;
		$lastime = strtotime($arr['create_time']);
		$arr['lastime'] = $this->lastime($lastime);
		if($arr){
			return $this->_toSuccess(['info' => $arr ,'list' => $lists,'like' => $arr['like'],'msg' => '获取成功']);
		}
		//print_r($user);
	}
	//获取所有帖子
    public function allThread()
    {
        $typeid  =  input('typeid');
		$uid  =  input('uid');
		$hot  =  input('hot');
		$page  =  input('page');
		$url = input('url');
		if($page>0){
			$limit = $page*3;
		}else{
			$limit = 3;
		}
		if($typeid == 0){
			// 查询所有
			$total = Thread::count()+3;
			if($total<$limit){
				return $this->_toError(['msg' => '没有更多了！']);
			}
			if($hot==0){
				$list = Thread::all(function($query) use($limit){
					$query->where('tid','>=', 1)->limit($limit)->order('tid', 'desc');
				});				
			}else{
				$list = Thread::all(function($query) use($limit){
					$query->where('tid','>=', 1)->limit($limit)->order('goodnums', 'desc');
				});				
			}

			$lists = [];
			if($list){
				 foreach($list as $arr){
					$arrname = User::get($arr['authorid']);
					$arr['url'] = $arrname['avatar'];
					$arr['author'] = $arrname['nickname'];
					//查看是否点赞当前用户
					$arrlike = Like::get(["tid"=>$arr['tid'],"uid"=>$uid,"pid"=>0]);
					$arr['like'] = $arrlike ? 1 : 0;
				    //查询帖子是否有图片
					$arrname = Album::all(["tid"=>$arr['tid']]);
                    
					if($arrname){
						$arrname = $arrname->toArray();
						$images = [];
						foreach($arrname as $arrn){
							
							$images[] = $url."/album/".$arrn['dir']."/".$arrn['filename'];
						}
	 
					//print_r($images);exit;
						$arr['imgList'] = $images;
						$arr['img_num'] = count($images);
					}else{
						$arr['img_num'] = 0;
						$arr['imgList'] = "";
					}
					$lastime = strtotime($arr['create_time']);
					$arr['lastime'] = $this->lastime($lastime);
					$lists[] = $arr;
				 }
				 return $this->_toSuccess(['list' => $lists ,'msg' => '获取成功']);
			}else{
				 return $this->_toError(['msg' => '获取失败']);
			}			
		}elseif($typeid > 0){
			// 指定分类
			$total = Thread::where('typeid',$typeid)->count()+3;
			if($total<$limit){
				return $this->_toError(['msg' => '没有更多了！']);
			}
			
			if($hot==0){
				$list = Thread::all(function($query) use($typeid,$limit){
				$query->where('typeid', $typeid)->limit($limit)->order('tid', 'desc');
			});			
			}else{
                $list = Thread::all(function($query) use($typeid){
				$query->where('typeid', $typeid)->limit($limit)->order('goodnums', 'desc');
			    });				
			}
			$lists = [];
			if($list){
				 foreach($list as $arr){
					$arrname = User::get($arr['authorid']);
					$arr['url'] = $arrname['avatar'];
					$arr['author'] = $arrname['nickname'];
					$arrlike = Like::get(["tid"=>$arr['tid'],"uid"=>$uid,"pid"=>0]);
					$arr['like'] = $arrlike ? 1 : 0;
					//查询帖子是否有图片
					$arrname = Album::all(["tid"=>$arr['tid']]);
                    
					if($arrname){
						$arrname = $arrname->toArray();
						$images = [];
						foreach($arrname as $arrn){
							$images[] = "/album/".$arrn['dir']."/".$arrn['filename'];
						}
	 
					//print_r($images);exit;
						$arr['imgList'] = $images;
						$arr['img_num'] = count($images);
					}else{
						$arr['img_num'] = 0;
						$arr['imgList'] = "";
					}
					$lastime = strtotime($arr['create_time']);
					$arr['lastime'] = $this->lastime($lastime);
					$lists[] = $arr;
				 }
				 return $this->_toSuccess(['list' => $lists ,'msg' => '获取成功']);
			}else{
				 return $this->_toError(['msg' => '获取失败']);
			}				
		}
 

    }	
//获取用户所有帖子
    public function myThread()
    {
    
		$uid  =  input('uid');
		$hot  =  input('hot');
		$page  =  input('page');
		$url = input('url');
		if($page>0){
			$limit = $page*3;
		}else{
			$limit = 3;
		}

			// 查询所有
			$total = Thread::count()+3;
			if($total<$limit){
				return $this->_toError(['msg' => '没有更多了！']);
			}
			 
				$list = Thread::all(function($query) use($limit,$uid){
					$query->where('authorid', $uid)->limit($limit)->order('tid', 'desc');
				});							 

			$lists = [];
			if($list){
				 foreach($list as $arr){
					$arrname = User::get($arr['authorid']);
					$arr['url'] = $arrname['avatar'];
					$arr['author'] = $arrname['nickname'];
					//查看是否点赞当前用户
					$arrlike = Like::get(["tid"=>$arr['tid'],"uid"=>$uid,"pid"=>0]);
					$arr['like'] = $arrlike ? 1 : 0;
				    //查询帖子是否有图片
					$arrname = Album::all(["tid"=>$arr['tid']]);
                    
					if($arrname){
						$arrname = $arrname->toArray();
						$images = [];
						foreach($arrname as $arrn){
							
							$images[] = $url."/album/".$arrn['dir']."/".$arrn['filename'];
						}
	 
					//print_r($images);exit;
						$arr['imgList'] = $images;
						$arr['img_num'] = count($images);
					}else{
						$arr['img_num'] = 0;
						$arr['imgList'] = "";
					}
					$lastime = strtotime($arr['create_time']);
					$arr['lastime'] = $this->lastime($lastime);
					$lists[] = $arr;
				 }
				 return $this->_toSuccess(['list' => $lists ,'msg' => '获取成功']);
			}else{
				 return $this->_toError(['msg' => '获取失败']);
			}			
	 

    }	
//获取用户点赞的帖子
    public function mylikeThread()
    {
    
		$uid  =  input('uid');
		$hot  =  input('hot');
		$page  =  input('page');
		$url = input('url');
		if($page>0){
			$limit = $page*3;
		}else{
			$limit = 3;
		}

			// 查询所有
			$total = Thread::count()+3;
			if($total<$limit){
				return $this->_toError(['msg' => '没有更多了！']);
			}
			//获取点赞记录
 
 
	 
			$list = Like::all(function($query) use($limit,$uid){
				$query->where('uid', $uid)->where('pid', 0)->limit($limit)->order('id', 'desc');
			});	
			$list = $list->toArray();
 					 

			$lists = [];
			if($list){
				 foreach($list as $arrs){
					
					$arr = Thread::get($arrs['tid']);
					$arrname = User::get($arr['authorid']);
					$arr['url'] = $arrname['avatar'];
					$arr['author'] = $arrname['nickname'];
					//查看是否点赞当前用户
					$arrlike = Like::get(["tid"=>$arr['tid'],"uid"=>$uid,"pid"=>0]);
					$arr['like'] = $arrlike ? 1 : 0;
				    //查询帖子是否有图片
					$arrname = Album::all(["tid"=>$arr['tid']]);
                    
					if($arrname){
						$arrname = $arrname->toArray();
						$images = [];
						foreach($arrname as $arrn){
							
							$images[] = $url."/album/".$arrn['dir']."/".$arrn['filename'];
						}
	 
					//print_r($images);exit;
						$arr['imgList'] = $images;
						$arr['img_num'] = count($images);
					}else{
						$arr['img_num'] = 0;
						$arr['imgList'] = "";
					}
					$lastime = strtotime($arr['create_time']);
					$arr['lastime'] = $this->lastime($lastime);
					$lists[] = $arr;
				 }
				 return $this->_toSuccess(['list' => $lists ,'msg' => '获取成功']);
			}else{
				 return $this->_toError(['msg' => '获取失败']);
			}			
	 

    }
    
    
    //转发分享
    public function share()
    {
        $tid = input("tid");
        $uid = input("uid");

        $share = Share::where("uid",$uid)->where("tid",$tid)->find();

        !$share && Share::insert([
            'tid' => $tid,
            'uid' => $uid,
            'create_time' => time()
        ]);

        //积分操作
        !$share && $this->makePoint($uid,$tid,3);

        Thread::where('tid',$tid)->setInc('sharenums',1);
    }


    //我的转发帖子
    public function myShare()
    {

        $uid  =  input('uid');
        $page  =  input('page');
        $url = input('url');
        if($page>0){
            $limit = $page*3;
        }else{
            $limit = 3;
        }

        $shares = Share::where("uid",$uid)->column('tid');
        if ($shares) {
            $sharsStr = implode(',',$shares);
        }else{
            return $this->_toError(['msg' => '暂无数据']);
        }

        // 查询所有
        $total = Thread::whereIn('tid',$sharsStr)->count()+3;
        if($total<$limit){
            return $this->_toError(['msg' => '没有更多了！']);
        }


        $list = Thread::all(function($query) use($limit,$uid,$sharsStr){
            $query->whereIn('tid', $sharsStr)->limit($limit)->order('tid', 'desc');
        });
        $lists = [];
        if($list){
            foreach($list as $arr){
                $arrname = User::get($arr['authorid']);
                $arr['url'] = $arrname['avatar'];
                $arr['author'] = $arrname['nickname'];
                //查看是否点赞当前用户
                $arrlike = Like::get(["tid"=>$arr['tid'],"uid"=>$uid,"pid"=>0]);
                $arr['like'] = $arrlike ? 1 : 0;
                //查询帖子是否有图片
                $arrname = Album::all(["tid"=>$arr['tid']]);

                if($arrname){
                    $arrname = $arrname->toArray();
                    $images = [];
                    foreach($arrname as $arrn){

                        $images[] = $url."/album/".$arrn['dir']."/".$arrn['filename'];
                    }
                    $arr['imgList'] = $images;
                    $arr['img_num'] = count($images);
                }else{
                    $arr['img_num'] = 0;
                    $arr['imgList'] = "";
                }

                $lists[] = $arr;
            }
            return $this->_toSuccess(['list' => $lists ,'msg' => '获取成功']);
        }else{
            return $this->_toError(['msg' => '获取失败']);
        }


    }
}
